//
//  NetworkTool+LCAVPlay.m
//  JKFuYinProject
//
//  Created by jiukuyinyue on 2017/9/30.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "NetworkTool+LCAVPlay.h"
#import "JKSongsMessStatus.h"
#import "AudioTool.h"

@implementation NetworkTool (LCAVPlay)

//判断下载的文件是否已经在沙盒中已经存在？
-(BOOL) isFileExist:(NSString *)fileName urlStr:(NSString *)urlStr{
    fileName = [fileName stringByReplacingOccurrencesOfString:@"file://" withString:@""];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:fileName];
    
    if (result) {
        result = YES;
    }else{
        result = NO;
    }
    NSLog(@"：%@",result?@"是的存在":@"不存在");
    return result;
}
//获取沙盒文件的大小
- (long long)getCacheFileSizeWithFilePath:(NSString *)filePath {
    NSFileManager  *fileMananger = [NSFileManager defaultManager];
    if ([fileMananger fileExistsAtPath:filePath]) {
        NSDictionary *dic = [fileMananger attributesOfItemAtPath:filePath error:nil];
        return [dic[@"NSFileSize"] longLongValue];
        //  return [[fileMananger attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    
    return 0;
}
//储存下来 下载文件的大小 , 用来以后判断是否存在
- (long long)getServerFileSizeWithUrlStr:(NSString *)urlStr {
    
    NSURL *url = [NSURL URLWithString:urlStr];
    // 可变请求对象
    NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url];
    // 设置请求方法为HEAD
    requestM.HTTPMethod = @"HEAD";
    // 准备响应对象
    NSURLResponse *response;
    // 发送同步请求
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    [NSURLConnection sendSynchronousRequest:requestM returningResponse:&response error:NULL];
#pragma clang diagnostic pop
//    [[NSUserDefaults standardUserDefaults] setInteger:(int)response.expectedContentLength forKey:urlStr];
    //出现异常所以不进行存储
    
    return response.expectedContentLength;
}

///NSString 转 url
- (NSURL *) configPlayerWithURL:(NSString *)urlString {
    NSURL *url = [NSURL URLWithString:urlString];
    return url;
}

///下载到沙盒
-(void)downloadSongWithUrl:(JKSongsMessStatus *)song{
    NSString *fileUrl = song.fileUrl;//网络url
    NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //    NSString *folder = [docDirPath stringByAppendingPathComponent:@"folder"];
    
    NSString *newStr = [fileUrl stringByReplacingOccurrencesOfString:@"/" withString:@""];
    newStr = [newStr stringByReplacingOccurrencesOfString:@":" withString:@""];
    newStr = [newStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    NSString *filePath = [NSString stringWithFormat:@"%@/%@", docDirPath ,newStr];
    //    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
    //    NSLog(@"filePath = %@", filePath);
    if (![kNetworkTool isFileExist:filePath urlStr:fileUrl]) {
        dispatch_async(dispatch_get_main_queue(), ^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
            [SVProgressHUD setInfoImage:nil];
#pragma clang diagnostic pop
            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom]; //自定义窗的 是黑色，字是白色
            [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
            [SVProgressHUD setBackgroundColor:[UIColor blackColor]];
            [SVProgressHUD setFont:[UIFont systemFontOfSize:13]];
            
            [SVProgressHUD showInfoWithStatus:@"已添加下载"];
            [SVProgressHUD dismissWithDelay:0.5];
            
        });
        //        NSData *data = [[NSData alloc]initWithContentsOfURL:url];
        //        [data writeToFile:filePath atomically:YES];//在沙盒Document目录下缓存文件
        
        [self downloadWithUrlStr:fileUrl savePath:filePath];
//        [kNetworkTool getServerFileSizeWithUrlStr:fileUrl];//储存文件的大小
//        NSLog(@"下载完毕: %s",__func__);
        
        NSDictionary *json = [song yy_modelToJSONObject];
        NSLog(@"_LCPlayer.downloadData = %@", _LCPlayer.downloadData);
        for (NSInteger i = 0; i < _LCPlayer.downloadData.count; i++) {
            NSDictionary *dict = _LCPlayer.downloadData[i];
            if ([json[@"title"] isEqualToString:dict[@"title"]]) {
                [_LCPlayer.downloadData removeObject:dict];
            }
        }
        [_LCPlayer.downloadData addObject:json];
        [[NSUserDefaults standardUserDefaults] setObject:_LCPlayer.downloadData.copy forKey:@"DOWNLOADONGS"];

    }else{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
        [SVProgressHUD setInfoImage:nil];
#pragma clang diagnostic pop
        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom]; //自定义窗的 是黑色，字是白色
        [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
        [SVProgressHUD setBackgroundColor:[UIColor blackColor]];
        [SVProgressHUD setFont:[UIFont systemFontOfSize:13]];
        
        [SVProgressHUD showInfoWithStatus:@"已存在"];
        [SVProgressHUD dismissWithDelay:0.5];

    }
    
}

- (void)downloadWithUrlStr:(NSString *)urlStr savePath:(NSString *)savePath{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 3.网络会话管理者发送GET请求
    [[manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress) {
        // downloadProgress : 下载进度
        NSLog(@"%f", downloadProgress.fractionCompleted);
    }                     destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        // destination : 有返回值的block(返回 文件下载完成后的临时缓存路径)
        // destination 里面需要自己设计文件缓存策略
        // targetPath : 文件下载完成后的临时缓存路径
        NSLog(@"targetPath %@", targetPath);
        
        // 会把字符串转URL,但是不会添加本地文件协议头(file://)
        //        NSURL *saveURL0 = [NSURL URLWithString:savePath];
        // 会把字符串转URL,并且会添加本地文件协议头(file://)
        NSURL *saveURL = [NSURL fileURLWithPath:savePath];
        
        // 返回的数据会交给completionHandler里面的filePath
        return saveURL;
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        // filePath : 文件下载完成后的临时缓存路径
        
        NSLog(@"URL=%@ - string=%@", filePath, filePath.path);
        [AudioTool playAudioWithName:@"download-complete.wav"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [AudioTool clearAudios];
        });
    }] resume];
    
    
    
}

///返回沙盒路径
- (NSString *)mp3WithUrl:(NSString *)fileUrl
{
    NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *newStr = [fileUrl stringByReplacingOccurrencesOfString:@"/" withString:@""];
    newStr = [newStr stringByReplacingOccurrencesOfString:@":" withString:@""];
    newStr = [newStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@", docDirPath ,newStr];
    return filePath;
}

//歌词沙盒路径
- (NSString *)lrcWithNewStr:(NSString *)newStr
{
    NSString *lrcDirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@.lrc", lrcDirPath ,newStr];
    return filePath;
}

//判断下载的文件是否已经在沙盒中已经存在？
- (BOOL) isFileExist:(NSString *)fileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:fileName];
    //    NSLog(@"：%@",result?@"歌词存在":@"歌词不存在");
    return result;
}

#pragma mark - 视频音频下载
- (void)lcDownloadMp4WithMg:(Mp4List *)mp4List :(LCMp4DetailModel *)mp4DetailModel
{
    NSString *fullPathName = [NSString stringWithFormat:@"/%@.mp4",mp4List.name];
    NSString *savePath = [LSZSpecialPackaging DownloadTheVideo:fullPathName];
    if ([kNetworkTool.downloadArray containsObject:savePath] && [kNetworkTool.downloading containsObject:mp4List.id]) {
        [SVProgressHUD showErrorWithStatus:@"该视频正在缓存!"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    NSArray *arrayGetData = [[NSArray alloc] initWithContentsOfFile:[LSZSpecialPackaging saveTheNameOfVideo]];
    for (NSDictionary *dic in arrayGetData) {
        NSString *name = NSStr(dic[@"title"]);
        NSString *id_id = NSStr(dic[@"id_id"]);
        if ([name isEqualToString:mp4List.name] && [id_id isEqualToString:mp4List.id]) {
            if([dic[@"style"] isEqualToString:@"1"]){
                [SVProgressHUD showErrorWithStatus:@"该视频已缓存过!"];
                [SVProgressHUD dismissWithDelay:1];
                return;
            }
        }
    }
    if (![kNetworkTool.downloadArray containsObject:savePath]) {
        [kNetworkTool.downloadArray addObject:savePath];
        [kNetworkTool.downloading addObject:mp4List.id];
    }
    [SVProgressHUD showWithStatus:@"缓存中....."];
    [SVProgressHUD dismissWithDelay:1];
    
    NSURL *url = [NSURL URLWithString:[mp4List.mp4_url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // 3.网络会话管理者发送GET请求
    [[kNetworkTool downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress) {
        // downloadProgress : 下载进度
        NSLog(@"%f", downloadProgress.fractionCompleted);
    }                     destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        // destination : 有返回值的block(返回 文件下载完成后的临时缓存路径)
        // destination 里面需要自己设计文件缓存策略
        // targetPath : 文件下载完成后的临时缓存路径
        NSLog(@"targetPath %@", targetPath);
        
        // 会把字符串转URL,但是不会添加本地文件协议头(file://)
        //        NSURL *saveURL0 = [NSURL URLWithString:savePath];
        // 会把字符串转URL,并且会添加本地文件协议头(file://)
        NSURL *saveURL = [NSURL fileURLWithPath:savePath];
        
        // 返回的数据会交给completionHandler里面的filePath
        return saveURL;
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        [kNetworkTool.downloadArray removeObject:[NSString stringWithFormat:@"%@",savePath]];
        
        // filePath : 文件下载完成后的临时缓存路径
                        NSLog(@"URL=%@ - string=%@", filePath, filePath.path);
        //        NSLog(@"下载完毕: %s",__func__);
        NSMutableArray *mutArrayAdd = [[NSMutableArray alloc] initWithArray:[[NSArray alloc] initWithContentsOfFile:[LSZSpecialPackaging saveTheNameOfVideo]]];
        NSString *style = @"1";//视频yes
        NSMutableDictionary *mutDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:mp4List.id,@"id_id",mp4List.name,@"title",mp4DetailModel.detail.pic,@"imageViewUrl",mp4DetailModel.detail.name,@"name",style,@"style",nil];
        [mutArrayAdd addObject:mutDic];
        [mutArrayAdd writeToFile:[LSZSpecialPackaging saveTheNameOfVideo] atomically:YES];
        [AudioTool playAudioWithName:@"download-complete.wav"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [AudioTool clearAudios];
        });
    }] resume];
}

@end
